package xing.application.service.isv.suite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xing.application.service.BaseService;
import xing.domain.isv.suite.CorpJSAPITicket;
import xing.domain.isv.suite.CorpSuiteAuth;
import xing.domain.isv.suite.DingConfig;
import xing.infrastructure.data.CallResult;
import xing.infrastructure.util.StringUtil;
import xing.repository.isv.suite.CorpAppRepository;
import xing.repository.isv.suite.CorpSuiteAuthRepository;

import java.security.MessageDigest;
import java.util.Formatter;
import java.util.List;

/********************************
 * 文 件 名 :DingConfigService.java
 * 创 建 人：陈天龙
 * 日    期：2017/8/28
 * 描   述：获取config传给前端
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class DingConfigService extends BaseService {

    @Autowired
    private CorpSuiteAuthRepository corpSuiteAuthRepository;
    @Autowired
    private CorpJSAPITicketService corpJSAPITicketService;
    @Autowired
    private CorpAppRepository corpAppRepository;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 描    述：获取config
     * 创 建 人：陈天龙
     * 日    期：2017/8/28
     * @param corpId
     * @param appId
     * @param url
     * @return CallResult
     */
    public CallResult getConfig(String corpId, Long appId,String url) throws Exception{
        logger.info("进入获取config的方法");
        long timeStamp = System.currentTimeMillis() / 1000;
        String nonceStr = StringUtil.getString(6);
        List<CorpSuiteAuth> corpSuiteAuths = corpSuiteAuthRepository.findAllByCorpId(corpId);
        CorpJSAPITicket corpJSAPITicket = new CorpJSAPITicket();
        if(null!=corpSuiteAuths && corpSuiteAuths.size()>0) {
            corpJSAPITicket = corpJSAPITicketService.getCorpJSAPITicket(corpSuiteAuths.get(0).getSuiteKey(),corpId);
        }else{
            return CallResult.error("请先创建一个套件");
        }
        String jsTicket = corpJSAPITicket.getCorpJsapiTicket();
        String sign = getSign(jsTicket,nonceStr,timeStamp,url);
        Long agentId = corpAppRepository.findByCorpIdAndAppId(corpId,appId).getAgentId();

        return CallResult.ok(new DingConfig(jsTicket,sign,nonceStr,timeStamp,corpId,agentId,appId));
    }

    /**
     * 描    述：获取sign
     * 创 建 人：陈天龙
     * 日    期：2017/8/28
     * @param ticket
     * @param nonceStr
     * @param timeStamp
     * @param url
     * @return CallResult
     */
    private String getSign(String ticket, String nonceStr, long timeStamp, String url) throws Exception{
        String plain = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + String.valueOf(timeStamp)
                + "&url=" + url;
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
            sha1.reset();
            sha1.update(plain.getBytes("UTF-8"));
            return bytesToHex(sha1.digest());
        } catch (Exception e) {
            logger.error("获取签名失败",e);
            throw e;
        }
    }

    private static String bytesToHex(byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
